<script setup>
import List from '../components/List.vue';
import ClusterNamespaceSelector from '../components/ClusterNamespaceSelector.vue'
import { getIngressListHandler as getListHandler, deleteIngressHandler as deleteHandler, getIngressTopologyHandler as getTopology } from '../../api/ingress.js';
import {reactive, computed, ref, toRefs} from 'vue'
import GenericOptions from '../components/GenericOptions.vue'
import { ElMessage,ElMessageBox  } from 'element-plus'
// import CodeMirror  from '../components/CodeMirror.vue'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import { useRouter } from 'vue-router';
import { DataSet,Network } from 'vis-network/standalone';
import { ar, hi } from 'element-plus/es/locales.mjs';
import Layout from '../layout/Layout.vue';
const router = useRouter()
const data = reactive({
  items: [],
  clusterId: "",
  namespace: "",
  topIngressName:"",
  yamlContent: ""
})
// 定义一个查询Pod列表的函数
const getList = () => {
  getListHandler({clusterId: data.clusterId, namespace: data.namespace}).then(
    (res) => {
      data.items = res.data.data.items
      console.log("items:",data.items)
    }
  )
}
// 回调函数
const rollback = (clusterId, namespace)=> {
  data.clusterId = clusterId
  data.namespace = namespace
  getList()
}
const search = ref('')
const filterTableData = computed(() => {
  if (!data.items) return [] // 如果 items 不存在，返回空数组
  return data.items.filter(item => 
    !search.value ||
    item.metadata?.name?.toLowerCase().includes(search.value.toLowerCase())
  )
})
// 展示详情
const showDetail = ref(false)
const detail = (row) => {
  const item = JSON.parse(JSON.stringify(row))
  // 删除managedFields
  delete item.metadata.managedFields
  // 把apiVersion kind补上去
  const itemtemp = {
    "apiVersion": "networking.k8s.io/v1",
    "kind": "Ingress",
    "metadata": item.metadata,
    "spec": item.spec
  }
  // 把当前数据转成yaml
  const yamlData = obj2Yaml(itemtemp)
  data.yamlContent = yamlData
  showDetail.value = true
}
//拓扑图展示
let showTop = ref(false)
const showTopology = async (row)=>{
  showTop.value = true
  data.topIngressName = row.metadata.name
  var nodes = null
  var edges = null
  //获取路由信息
  await getTopology({clusterId: data.clusterId, namespace: data.namespace, name: row.metadata.name}).then(
    (res) => {
      nodes = res.data.data.nodes
      edges = res.data.data.edges
      console.log("items:",nodes)
      console.log("items:",edges)
    }
  )
       // create a network
       var container = document.getElementById("mynetwork");
       var visData = {
        nodes: nodes,
        edges: edges,
      };
      var options = {
        edges: {
          //箭头
          arrows: {
            to: {
              enabled: true,
            }
          },
        },
        nodes: {
          //阴影
          shadow: true,
          color: {
            border: "#c2ccd0",
            background: "#c2ccd0",
          }
        },
        layout: {
          //定义层次结构的
          hierarchical: {
            sortMethod: "directed",
            direction: "UD",
            levelSeparation: 100,
          },
        }
      };
      var network = new Network(container, visData, options);
}
const {yamlContent,clusterId,namespace,topIngressName} = toRefs(data)
const handleChange = (value) => {
  console.log(value)
}
</script>

<template>
  <List title="Ingress列表">
    <template #header-options>
      <ClusterNamespaceSelector @namespaceChangedRollback="rollback">

      </ClusterNamespaceSelector>
      <el-input v-model="search" size="small" placeholder="搜索" style="width: 140px; margin-left: 10px; height: 32px;" />
    </template>
    <template #main>
      <el-table
      border 
      height="480" 
      :data="filterTableData" 
      style="width: 100%"
      :default-sort="{prop: 'metadata.creationTimestamp', order: 'descending'}"
      >
        <el-table-column fixed prop="" align="center" label="名称">
          <template #default="scope">
            <el-button link type="primary"  @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="spec.ingressClassName" align="center" label="IngressClass名称" width="240" />
        <el-table-column  prop="" align="center" label="域名和路径" width="240">
          <template #default="scope">
            <!-- 拿到了某个路由配置 -->
            <template v-for="rule in scope.row.spec.rules">
              <!-- 拿到了某个路径的配置 -->
              <span style="display: block;" v-for="path in rule.http.paths">
                <!-- host: baidu.com  path: /api  -> baidu.com/api -->
               <li style="text-align: left;">{{ rule.host }}{{ path.path }}</li> 
              </span>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="metadata.namespace" align="center" label="命名空间" width="240" />
        <el-table-column fixed="right" align="center" label="操作" width="320" >
          <template #default="scope">
            <GenericOptions
            v-on:delete-rollback="getList"
            :name="scope.row.metadata.name"
            :cluster-id="clusterId"
            :disabled ="scope.row.metadata.deletionTimestamp" 
            resource-type="Ingress"
            :namespace="scope.row.metadata.namespace"
            >
            </GenericOptions>
            <el-button link type="primary" @click="showTopology(scope.row)">拓扑图</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </List>
  <DialogYaml
  :cluster-id="data.clusterId"
  :namespace="data.namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
  <el-dialog append-to-body width="70%" center draggable v-model="showTop">
        <template #header="{ titleId, titleClass }">
            <div class="my-header">
                <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
                  <el-tag  class="el-tag" size="large" title="集群">
                    {{ clusterId }}
                  </el-tag>
                  >
                  <el-tag class="el-tag"  size="large" title="命名空间">
                    {{ namespace }}
                  </el-tag>
                  >
                  <el-tag class="el-tag"  size="large" title="资源名称">
                    {{ topIngressName }}
                  </el-tag>
                </div>
            </div>
        </template>
        <div style="width:100%" id="mynetwork">
         
        </div>
    </el-dialog>
  <!-- <el-dialog
  v-model="showDetail" 
  width="70%">
  <template #header="{ titleId, titleClass }">
    <div class="my-header">
      <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
        <el-button type="primary" title="资源所在的集群" >
          <i class="iconfont icon-kubernetes" style="font-size: 20px;" />
          <span style="font-size: 20px;margin-left: 10px;">{{ data.clusterId }}</span>
        </el-button>
        <el-button type="primary" title="资源所在的命名空间" >
          <i class="iconfont icon-Namespace" style="font-size: 20px;" />
          <span style="font-size: 20px;margin-left: 10px;">{{ data.namespace }}</span>
        </el-button>
      </div>
    </div>
  </template>
    <CodeMirror
    v-model="yamlContent"
    ></CodeMirror>
  </el-dialog> -->
</template>

<style scoped>
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
#mynetwork {
  width: 600px;
  height: 400px;
  border: 1px solid lightgray;
}
</style>
